package com.wangwenjun.concurrency.chapter14.atomicreference;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import static java.util.concurrent.ThreadLocalRandom.current;

/**
 * @author wyaoyao
 * @date 2021/4/19 17:19
 */
public class AtomicReferenceExample2 {

    private static AtomicReference<DebitCard> ar = new AtomicReference(new DebitCard("张三", 0));

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1000);
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                while (true) {
                    DebitCard old = ar.get();
                    DebitCard dc = new DebitCard(old.getAccount(), old.getAmount() + 10);
                    if (ar.compareAndSet(old, dc)) {
                       break;
                    }
                }
                countDownLatch.countDown();
            }, "T-" + i).start();
        }


        countDownLatch.await();

        System.out.println("end:"+ar.get());
    }
}
